'''
Author: caishuyang
Date: 2023-03-03 19:24:43
LastEditors: caishuyang
LastEditTime: 2023-03-06 10:12:11
Description: 串口通信
'''
import serial
import time
import torch
from queue import Queue
import random

class mySerial():
    def __init__(self, port="com13", baudrate=115200, timeout=0.5):
        self.port = port
        self.baudrate = baudrate
        self.timeout = timeout
        self.flag = True
        self.ser = None

    def open_ser(self):
        try:
            self.ser = serial.Serial(
                self.port, self.baudrate, timeout=self.timeout)
            if (self.ser.isOpen() == True):
                print("串口打开成功")
        except Exception as exc:
            self.flag = False
            print("串口打开异常", exc)

    def read_msg(self,q):
        try:
            print("等待接收数据")
            while self.flag:
                ori_data = self.ser.read(self.ser.in_waiting).decode("utf-8")
                ori_data = ori_data.split("\t")
                if len(ori_data >= 9):
                    data = []
                    for i in range(9):
                        if not ori_data[i].isdigit:
                            ori_data[i] = ori_data[i].split("\n")[0]
                        if i != 3: #经过排查发现4号传感器存在问题
                            data.append(int(ori_data[i]))
                    data=torch.tensor([data]) #转化成tensor类型
                    #print("已接受到数据:", data)
                    if q.full():
                        q.get()
                    q.put(data)
                    time.sleep(0.01)
        except Exception as exc:
            print("读取异常", exc)

    def imitate_read(self,q):
        '''
            模拟信号发射
        '''
        try:
            
            while self.flag:
                k=50*random.random()
                lis=[1358,2080.0,1310,1559,2866.0,3121,1300,1475]
                data=torch.tensor([lis])
                data+=k-25
                k+=10
                if q.full():
                    q.get()
                q.put(data)
                #print(data)
                time.sleep(0.01)
        except Exception as exc:
            self.flag = False
            print("模拟发送异常:", exc)
            
    def close_ser(self):
        try:
            self.ser.close()
            if self.ser.isOpen():
                print("串口未关闭")
            else:
                print("串口已关闭")
        except Exception as exc:
            print("串口关闭异常", exc)




if __name__ == '__main__':
    myser = mySerial()
    q=Queue(maxsize=1)
    myser.open_ser()
    myser.read_msg(q=q)
    myser.close_ser()
    